import { Component, OnInit, ViewChild, ViewContainerRef, ComponentRef, ComponentFactoryResolver, EventEmitter } from '@angular/core';
import { AppPaginationComponent, PaginationModel } from "../../../../../widgets/pagination/pagination.component";
import { DataService } from '../../../../../services/data.service'
import { EditComponent } from "../../modal/edit/edit.component";
import { AddComponent } from "../../modal/add/add.component"
import { ModifyComponent } from "../../modal/modify/modify.component"
import { DeleteComponent } from "../../modal/delete/delete.component"
import { AuditComponent } from "../../modal/audit/audit.component"
import { WithdrawComponent } from "../../modal/withdraw/withdraw.component"
import { NQdiigmService } from "./n-qdiigm.service"
import * as _ from "lodash";

@Component({
  selector: 'app-n-qdiigm',
  templateUrl: './n-qdiigm.component.html',
  styleUrls: ['./n-qdiigm.component.scss'],
  providers: [NQdiigmService],
})
export class NQDIIgmComponent implements OnInit {
  //查看#edit modal1
  @ViewChild("edit", { read: ViewContainerRef })
  edit: ViewContainerRef;
  editComponent: ComponentRef<EditComponent>;

  //添加#add modal2
  @ViewChild("add", { read: ViewContainerRef })
  add: ViewContainerRef;
  addComponent: ComponentRef<AddComponent>;

  //修改#modify modal3
  @ViewChild("modify", { read: ViewContainerRef })
  modify: ViewContainerRef;
  modifyComponent: ComponentRef<ModifyComponent>;

  //删除#delete modal4
  @ViewChild("delete", { read: ViewContainerRef })
  delete: ViewContainerRef;
  deleteComponent: ComponentRef<DeleteComponent>;

  //审核#audit modal5
  @ViewChild("audit", { read: ViewContainerRef })
  audit: ViewContainerRef;
  auditComponent: ComponentRef<AuditComponent>;

  //撤销#withdraw modal6
  @ViewChild("withdraw", { read: ViewContainerRef })
  withdraw: ViewContainerRef;
  withdrawComponent: ComponentRef<WithdrawComponent>;

  // lodash
  public _: any = _;

  // 菜单数据
  public menuData: any;
  // 菜单权限set
  public menuResourceSet: any = [];
  //列表数据
  public listData: any = [];
  //列表全选
  public isCheckedAll: any = false;

  //分页配置
  public listPageInfo = {
    currentPageNum: 1,
    pageSize: 50,
    totalPages: 1,
    total: 0,
    pagesShow: 5,
    startRow: 0,
    endRow: 0,
    pageList: [5, 10, 25, 50, 100]
  };

  //查询列表getBody
  public getBody: any = {
    pageIndex: 1,
    pageSize: 50,
    sType: 0,
    sFgName: '',
    sFgDesc: '',
    sMemberTemp: '',
    sStatus: ''
  };

  constructor(
    public resolver: ComponentFactoryResolver,
    public nQdiigmService: NQdiigmService,
    public dataService: DataService,
  ) { }

  ngOnInit() {
    let that = this;
    this.loadlist();
    // 关闭添加模态框
    this.dataService.rcmiEditEmitter = new EventEmitter();
    this.dataService.rcmiEditEmitter.subscribe((value: any) => {
      window['$']('#edit').modal('hide');
      window['$']('#add').modal('hide');
      window['$']('#modify').modal('hide');
      window['$']('#delete').modal('hide');
      window['$']('#audit').modal('hide');
      window['$']('#withdraw').modal('hide');
      this.loadlist();
    });
    // 权限处理
    this.dataService.initTree.subscribe((data) => {
      if (data) {
        let SessionMenuData = sessionStorage.getItem('menu');
        this.menuData = JSON.parse(SessionMenuData)
        this.menuResourceSet = [];
        _.forEach(this.menuData, (item, index) => {
          if (item.sName == '风控管理') {
            _.forEach(item.children, (it, idx) => {
              if (it.sName == '非QDII基金组管理') {
                that.menuResourceSet = it.resourceSet
                sessionStorage.setItem('btn-NQDIIm', this.menuResourceSet);
              }
            })
          }
        })
      }
    })
    let SessionMenuData = sessionStorage.getItem('menu');
    this.menuData = JSON.parse(SessionMenuData)
    this.menuResourceSet = [];
    _.forEach(this.menuData, (item, index) => {
      if (item.sName == '风控管理') {
        _.forEach(item.children, (it, idx) => {
          if (it.sName == '非QDII基金组管理') {
            that.menuResourceSet = it.resourceSet
            sessionStorage.setItem('btn-NQDIIm', this.menuResourceSet);
          }
        })
      }
    })
    // console.info(this.menuResourceSet)
  }

  // 列表全选
  checkedAll() {
    this.isCheckedAll = false;
    console.log(this.isCheckedAll);
  }

  // 列表只能单选
  ctrlCheckAll(index) {
    let that = this;
    _.forEach(this.listData, (item, idx) => {
      if (idx == index && item.isChecked == true) {
        item.isChecked = true;
      }
      else {
        item.isChecked = false;
      }
    })
  }

  //分页列表
  loadlist(pageNum?, pageSize?) {
    let that = this;
    this.isCheckedAll = false;
    this.getBody.sFgName = _.trim(this.getBody.sFgName);
    console.log(this.getBody.sFgDesc);
    this.getBody.sFgDesc = _.trim(this.getBody.sFgDesc);
    this.getBody.sMemberTemp = _.trim(this.getBody.sMemberTemp);
    // 查询条件转码
    this.getBody.pageIndex = pageNum ? pageNum : this.listPageInfo.currentPageNum;
    this.getBody.pageSize = pageSize ? pageSize : this.listPageInfo.pageSize;
    this.nQdiigmService.list(this.getBody).subscribe(data => {
      if (data) {
        this.listData = data.list;
        console.log(data.list);
        this.listPageInfo.currentPageNum = data.pageNum;
        this.listPageInfo.totalPages = data.pages;
        this.listPageInfo.total = data.total;
        this.listPageInfo.startRow = data.startRow;
        this.listPageInfo.endRow = data.endRow;
      }
    })
  }
  // 条数分页
  sizeChange(pageSize: number) {
    if (pageSize !== this.listPageInfo.pageSize) {
      this.listPageInfo.pageSize = pageSize;
      this.loadlist();
    }
  }
  // 列表分页
  pageNavigation(currentPageNum: number) {
    this.listPageInfo.currentPageNum = currentPageNum;
    this.loadlist(this.listPageInfo.currentPageNum, this.listPageInfo.pageSize);
  }


  //显示查看#edit modal1
  showEditModal(type, item?) {
    let that = this;
    switch (type) {
      case "dbclick":
        this.showEdit(item);
        window['$']('#edit').modal('show');
        break;
      case "one":
        let checkProduct = [];
        _.forEach(this.listData, item => {
          if (item.isChecked == true) {
            checkProduct.push(item);
          }
        })
        if (checkProduct.length == 0) {
          window['swal']("注意", "请选择一条记录进行查看!", "warning")
        }
        else if (checkProduct.length == 1) {
          this.showEdit(checkProduct[0]);
          window['$']('#edit').modal('show');
        }
        else {
          window['swal']("注意", "只能选择一条记录进行查看!", "warning")
        }
        break;
    }
  }
  //显示添加#add modal2
  showAddModal() {
    this.showAdd();
    window['$']('#add').modal('show');
  }
  //显示修改#modify modal3
  showModifyModal() {
    let that = this;
    let checkProduct = [];
    _.forEach(this.listData, item => {
      if (item.isChecked == true) {
        checkProduct.push(item);
      }
    })
    if (checkProduct.length == 0) {
      window['swal']("注意", "请选择一条记录进行修改!", "warning")
    }
    else if (checkProduct[0].sStatus == "删除待审") {
      window['swal']("注意", "不支持修改删除待审!", "warning")
    }
    else if (checkProduct[0].sFgMemberValid == "*ALL") {
      //这里还要添加判断 
      //选择了群组成员为全部的非QDII基金的数据，即群组成员为“*ALL”的记录，点击【修改】按钮，系统提示：该基金组包括全部的非QDII基金，不能修改！
      window['swal']("注意", "该基金组包括全部的非QDII基金，不能修改！", "warning")
    }
    else {
      this.showModify(checkProduct[0]);
      window['$']('#modify').modal('show');
    }
  }

  //显示删除#delete modal4
  showDeleteModal() {
    let that = this;
    let checkProduct = [];
    _.forEach(this.listData, item => {
      if (item.isChecked == true) {
        checkProduct.push(item);
      }
    })

    if (checkProduct.length == 0) {
      window['swal']("注意", "请选择一条记录进行删除!", "warning")
    }
    else if (checkProduct[0].sStatus == "修改待审") {
      window['swal']("注意", "不支持删除修改待审!", "warning");
    }
    else if (checkProduct[0].sStatus == "删除待审") {
      window['swal']("注意", "当前状态已为删除待审，请勿重复操作!", "warning");
    }
    else {
      that.showDelete(checkProduct[0]);
      window['$']('#delete').modal('show');
    }
  }

  //显示审核#audit modal5
  showAuditModal() {
    let that = this;
    let checkProduct = [];
    _.forEach(this.listData, item => {
      if (item.isChecked == true) {
        checkProduct.push(item);
      }
    })
    if (checkProduct.length == 0) {
      window['swal']("注意", "请选择一条记录进行审核!", "warning")
    }
    else if (checkProduct.length == 1) {
      console.log(checkProduct[0]);
      if (checkProduct[0].sStatus == "正常") {
        window['swal']("注意", "正常状态不需要审核!", "warning")
      } else {
        let auditRightReturn: any;
        //审核权限auditRightBody
        let auditRightBody: any = {
          nFgId: checkProduct[0].nFgId,
          sFgName: checkProduct[0].sFgName,
          sFgDesc: checkProduct[0].sFgDesc,
          sFgMemberValid: checkProduct[0].sFgMemberValid,
          sMemberTemp: checkProduct[0].sMemberTemp,
          sType: checkProduct[0].sType,
          sMemberFundnos: checkProduct[0].sMemberFundnos
        };
        console.log(auditRightBody);
        this.nQdiigmService.auditRight(auditRightBody).subscribe(data => {
          console.log(JSON.stringify(data));
          if (data.sStatus == 'Y') {
            this.showAudit(checkProduct[0], data);
            window['$']('#audit').modal('show');
          } else if (data.sStatus == 'N') {
            window['swal']("注意", "不能审核本人提交的记录!", "warning")
          }
        });

      }
    }
    else {
      window['swal']("注意", "只能选择一条记录进行审核!", "warning")
    };
  }
  //显示撤销#withdraw modal6
  showWithdrawModal() {
    let that = this;
    let checkProduct = [];
    _.forEach(this.listData, item => {
      if (item.isChecked == true) {
        checkProduct.push(item);
      }
    })
    if (checkProduct.length == 0) {
      window['swal']("注意", "请选择一条记录进行撤销!", "warning")
    }
    else if (checkProduct.length == 1) {
      if (checkProduct[0].sStatus == "正常") {
        window['swal']("注意", "正常状态不能进行撤销!", "warning")
      } else {
        let auditRightReturn: any;
        //审核权限auditRightBody
        let auditRightBody: any = {
          nFgId: checkProduct[0].nFgId,
          sFgName: checkProduct[0].sFgName,
          sFgDesc: checkProduct[0].sFgDesc,
          sFgMemberValid: checkProduct[0].sFgMemberValid,
          sMemberTemp: checkProduct[0].sMemberTemp,
          sType: checkProduct[0].sType
        };
        this.nQdiigmService.auditRight(auditRightBody).subscribe(data => {
          console.log(data);
          if (data.sStatus == 'Y') {
            window['swal']("注意", "不能撤销非本人提交的记录!", "warning");
          } else if (data.sStatus == 'N') {
            this.showWithdraw(checkProduct[0]);
            window['$']('#withdraw').modal('show');
          }
        });

      }
    }
    else {
      window['swal']("注意", "只能选择一条记录进行撤销!", "warning")
    }
  }


  //查看#edit modal1创建
  showEdit(item) {
    // 判断组件是否已创建，如果创建先注销
    if (this.editComponent && this.editComponent.instance) {
      this.editComponent.destroy();
    }
    // 动态创建组件的实例
    const editComponent = this.resolver.resolveComponentFactory(EditComponent);
    this.editComponent = this.edit.createComponent(editComponent);
    console.log(item);
    this.editComponent.instance.item = item;
  }

  //添加#add modal2创建
  showAdd() {
    // 判断组件是否已创建，如果创建先注销
    if (this.addComponent && this.addComponent.instance) {
      this.addComponent.destroy();
    }
    // 动态创建组件的实例
    const addComponent = this.resolver.resolveComponentFactory(AddComponent);
    this.addComponent = this.add.createComponent(addComponent);
    this.addComponent.instance.sType = '0';
  }

  //修改#modify modal3创建
  showModify(item) {
    let getbody = {
      nFgIdList: []
    }
    getbody.nFgIdList.push(item.nFgId);
    this.nQdiigmService.addLock(getbody).subscribe((data) => {
      if (data == true) {
        // 判断组件是否已创建，如果创建先注销
        if (this.addComponent && this.addComponent.instance) {
          this.addComponent.destroy();
        }
        // 判断组件是否已创建，如果创建先注销
        if (this.modifyComponent && this.modifyComponent.instance) {
          this.modifyComponent.destroy();
        }
        // 动态创建组件的实例
        const modifyComponent = this.resolver.resolveComponentFactory(ModifyComponent);
        this.modifyComponent = this.modify.createComponent(modifyComponent);
        this.modifyComponent.instance.item = item;
        console.log(item);
      }
      else {
        window['swal']("注意", "加锁失败!", "warning")
      }
    })

  }

  //删除#delete modal4创建
  showDelete(item) {
    // 判断组件是否已创建，如果创建先注销
    if (this.deleteComponent && this.deleteComponent.instance) {
      this.deleteComponent.destroy();
    }
    // 动态创建组件的实例
    const deleteComponent = this.resolver.resolveComponentFactory(DeleteComponent);
    this.deleteComponent = this.delete.createComponent(deleteComponent);
    this.deleteComponent.instance.item = item;
  }

  //审核#audit modal5创建
  showAudit(item, Status?) {
    // 判断组件是否已创建，如果创建先注销
    if (this.auditComponent && this.auditComponent.instance) {
      this.auditComponent.destroy();
    }
    // 动态创建组件的实例
    const auditComponent = this.resolver.resolveComponentFactory(AuditComponent);
    this.auditComponent = this.audit.createComponent(auditComponent);
    this.auditComponent.instance.item = item;
    this.auditComponent.instance.list = Status;
  }

  //撤销#withdraw modal6创建
  showWithdraw(item) {
    let getbody = {
      nFgIdList: []
    }
    getbody.nFgIdList.push(item.nFgId);
    this.nQdiigmService.addLock(getbody).subscribe((data) => {
      if (data == true) {
        // 判断组件是否已创建，如果创建先注销
        if (this.withdrawComponent && this.withdrawComponent.instance) {
          this.withdrawComponent.destroy();
        }
        // 动态创建组件的实例
        const withdrawComponent = this.resolver.resolveComponentFactory(WithdrawComponent);
        this.withdrawComponent = this.withdraw.createComponent(withdrawComponent);
        this.withdrawComponent.instance.item = item;
      }
      else {
        window['swal']("注意", "加锁失败!", "warning")
      }
    })

  }
}
